package com.example.harmonyos_orm.ui.slice;

import com.example.harmonyos_orm.ResourceTable;
import com.example.harmonyos_orm.app.BaseAbilitySlice;
import com.example.harmonyos_orm.data.Ip;
import com.example.harmonyos_orm.database.PhotoDatabase;
import com.example.harmonyos_orm.database.PhotoItem;
import com.example.harmonyos_orm.net.Network;
import com.zhushenwudi.hmutils.adapter.SuperProvider;
import com.zhushenwudi.hmutils.net.HttpBean;
import com.zhushenwudi.hmutils.net.RequestBaseObserver;
import com.zhushenwudi.hmutils.utils.Log;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.window.dialog.CommonDialog;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.utils.zson.ZSONObject;

import java.util.List;

import static com.example.harmonyos_orm.net.Network.api;

public class MainAbilitySlice extends BaseAbilitySlice implements Component.ClickedListener {
    private List<PhotoItem> photoItemList;
    private ListContainer mListContainer;
    private SuperProvider photoProvider;
    private OrmContext photoDB;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }

    private void initView() {
        Button mInsertBtn = (Button) findComponentById(ResourceTable.Id_insertBtn);
        Button mQueryBtn = (Button) findComponentById(ResourceTable.Id_queryBtn);
        Button mGetBtn = (Button) findComponentById(ResourceTable.Id_getBtn);
        Button mPostBtn = (Button) findComponentById(ResourceTable.Id_postBtn);
        mListContainer = (ListContainer) findComponentById(ResourceTable.Id_listContainer);
        mInsertBtn.setClickedListener(this);
        mQueryBtn.setClickedListener(this);
        mGetBtn.setClickedListener(this);
        mPostBtn.setClickedListener(this);
        mListContainer.setItemClickedListener((listContainer, component, i, l) -> {
            PhotoItem item = (PhotoItem) listContainer.getItemProvider().getItem(i);
            CommonDialog commonDialog = new CommonDialog(this);
            commonDialog.setSize(900, 500);
            commonDialog.setContentText("确定删除第" + (i + 1) + "张图片吗？");
            commonDialog.setButton(1, "确定", (iDialog, i1) -> {
                photoItemList.remove(item);
                photoProvider.notifyDataSetItemRemoved(i);
                photoDB.delete(item);
                photoDB.flush();
                iDialog.hide();
            });
            commonDialog.show();
        });
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            // 插入数据
            case ResourceTable.Id_insertBtn:
                int[] res = new int[]{ResourceTable.Media_fff, ResourceTable.Media_eee, ResourceTable.Media_ddd,
                        ResourceTable.Media_ccc, ResourceTable.Media_bbb, ResourceTable.Media_aaa};
                for (int i = 0; i < 6; i++) {
                    OrmPredicates predicates = photoDB.where(PhotoItem.class).equalTo("id", i + 1);
                    insertOrReplace(res[i], predicates);
                }
                break;
            // 查询数据
            case ResourceTable.Id_queryBtn:
                photoItemList.clear();
                photoItemList.addAll(query());
                if (photoItemList.isEmpty()) return;
                photoProvider.notifyDataChanged();
                break;
            // GET请求
            case ResourceTable.Id_getBtn:
                getIp();
                break;
            // POST请求
            case ResourceTable.Id_postBtn:
                postIp();
                break;
        }
    }

    public List<PhotoItem> query() {
        OrmPredicates ormPredicates = photoDB.where(PhotoItem.class);
        return photoDB.query(ormPredicates);
    }

    public boolean insertOrReplace(int path, OrmPredicates predicates) {
        List<PhotoItem> itemInDBList = photoDB.query(predicates);
        if (itemInDBList.size() > 0) {
            PhotoItem itemInDB = itemInDBList.get(0);
            // 改
            itemInDB.setPath(path);
            photoDB.update(itemInDB);
        } else {
            // 增
            photoDB.insert(new PhotoItem(path));
        }
        return photoDB.flush();
    }

    /**
     * GET请求
     */
    private void getIp() {
        request(api().getIp("114.114.114.114"))
                .subscribe(new RequestBaseObserver<HttpBean<Ip>>(sp) {
                    @Override
                    public void onSuccess(HttpBean<Ip> t) {
                        Log.e("success");
                    }

                    @Override
                    public void onError(String msg) {
                        Log.e("fail");
                    }
                });
    }

    /**
     * POST请求
     */
    private void postIp() {
        ZSONObject obj = new ZSONObject();
        obj.put("ip", "114.114.114.114");
        request(api().postIp(Network.createBody(obj)))
                .subscribe(new RequestBaseObserver<HttpBean<Ip>>(sp) {
                    @Override
                    public void onSuccess(HttpBean<Ip> t) {
                        Log.e("success");
                    }

                    @Override
                    public void onError(String msg) {
                        Log.e("fail");
                    }
                });
    }

    @Override
    public void onActive() {
        super.onActive();
        // 初始化数据库
        photoDB = dataHelper.selectTable(PhotoDatabase.class);
        photoItemList = query();
        photoProvider = new SuperProvider<>(photoItemList, this);
        mListContainer.setItemProvider(photoProvider);
    }

    @Override
    protected void onInactive() {
        // 关闭数据库
        photoDB.close();
        super.onInactive();
    }
}
